package com.lianxi.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.lianxi.dao.Pager;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ESearchUtils<T> {
    private static final Logger logger = LoggerFactory.getLogger(ESearchUtils.class);

    public Pager<T> searchUser(String index,
                                   String name,
                                   Pager<T> pager) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("index", index);
        String filters = "";
        filters += "name:" + name;
        /*        filters += ",status:" + ClueConstants.DELETE_CLUE_TAKE_NOT;*/
        paramMap.put("filters", filters);
        OkHttpUtils okHttpUtils = OkHttpUtils.newInstance();
        String requestParam = JSON.toJSONString(paramMap);
//        Response response = okHttpUtils.doPost(ResourcesUtils.getESUrl(), requestParam);
        Response response = okHttpUtils.doGet(ResourcesUtils.getESUrl());
        return getEsPager(response, pager);
    }

    public Pager<T> searchClueTask(String index,
                                   int userId,
                                   String keyWords,
                                   int level,
                                   String beginTime,
                                   String endTime,
                                   Pager<T> pager) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("index", index);
        String filters = "";
        filters += "user_id:" + userId;
/*        filters += ",status:" + ClueConstants.DELETE_CLUE_TAKE_NOT;*/
        if (level != -1) {
            filters += ",level:" + level;
        }
        paramMap.put("filters", filters);
        String highlightFields = "clue_name,username";
        paramMap.put("highlightFields", highlightFields);
        String keywordsFields = "clue_name,username";
        paramMap.put("keywordsFields", keywordsFields);
        if (StringUtils.isNotBlank(keyWords)) {
            paramMap.put("keywords", keyWords);
        }
        if (StringUtils.isNotBlank(beginTime)) {
            Date beginTimeDate = DateUtil.format(beginTime, "yyyy-M-d");
            paramMap.put("beginTime", "take_time@" + DateUtil.format(beginTimeDate, "yyyy-MM-dd") + " 00:00:00");
        }
        if (StringUtils.isNotBlank(endTime)) {
            Date endTimeDate = DateUtil.format(endTime, "yyyy-M-d");
            paramMap.put("endTime", "take_time@" + DateUtil.format(endTimeDate, "yyyy-MM-dd") + " 23:59:59");
        }
        paramMap.put("refTime", "take_time");
        OkHttpUtils okHttpUtils = OkHttpUtils.newInstance();
        String requestParam = JSON.toJSONString(paramMap);
        Response response = okHttpUtils.doPost(ResourcesUtils.getESUrl(), requestParam);
        return getEsPager(response, pager);
    }


    /**
     * 检索线索的ES方法
     *
     * @param keyWords  关键词
     * @param index     检索的库表
     * @param beginTime 开始时间
     * @param endTime   结束时间
     * @param pager     分页数据
     * @return 查询结果
     */
    public Pager<T> searchClueList(String index,
                                   int userId,
                                   int sourceId,
                                   String keyWords,
                                   int level,
                                   String beginTime,
                                   String endTime,
                                   String depIds,
                                   int sortType,
                                   Pager<T> pager) {

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("index", index);
        String filters = "";

        if (userId > 0) {
            filters += "uid:" + userId;
//            filters += ",status:" + ClueConstants.STATUS_OF_NORMAL;
        } else {
//            filters += "status:" + ClueConstants.STATUS_OF_NORMAL;
        }
        if (sourceId > 0) {
            filters += ",source_id:" + sourceId;
        }
        if (StringUtils.isNotBlank(depIds)) {
            filters += ",";
            depIds = depIds.replace(",", "#");
            filters += "min_dep_id:" + depIds;
        }

        paramMap.put("filters", filters);
        String highlightFields = "name,content,founder";
        paramMap.put("highlightFields", highlightFields);
        String keywordsFields = "name,content,founder";
        paramMap.put("keywordsFields", keywordsFields);
        if (StringUtils.isNotBlank(keyWords)) {
            paramMap.put("keywords", keyWords);
        }
        if (StringUtils.isNotBlank(beginTime)) {
            Date beginTimeDate = DateUtil.format(beginTime, "yyyy-M-d");
            paramMap.put("beginTime", "create_time@" + DateUtil.format(beginTimeDate, "yyyy-MM-dd") + " 00:00:00");
        }
        if (StringUtils.isNotBlank(endTime)) {
            Date endTimeDate = DateUtil.format(endTime, "yyyy-M-d");
            paramMap.put("endTime", "create_time@" + DateUtil.format(endTimeDate, "yyyy-MM-dd") + " 23:59:59");
        }
        paramMap.put("pageNumber", pager.getPage());
        if (pager.getLength() == 0) {
            pager.setLength(15);
        }
        paramMap.put("pageSize", pager.getLength());
        OkHttpUtils okHttpUtils = OkHttpUtils.newInstance();
        String requestParam = JSON.toJSONString(paramMap);
        Response response = okHttpUtils.doPost(ResourcesUtils.getESUrl(), requestParam);
        return getEsPager(response, pager);
    }


    public Pager<T> searchList(String keywordsFields,
                               String keyWord,
                               String index,
                               String beginTime,
                               String endTime,
                               String type,
                               Pager<T> pager,
                               int userId,
                               int isFilters) {
        OkHttpUtils okHttpUtils = OkHttpUtils.newInstance();
        Map<String, Object> map = new HashMap<>();
        Date beginTimeDate = DateUtil.format(beginTime, "yyyy-M-d");
        Date endTimeDate = DateUtil.format(endTime, "yyyy-M-d");
        if (isFilters > 0) {
            map.put("filters", type);
        }
        map.put("pageNumber", pager.getPage());
        map.put("pageSize", pager.getLength());
        if (StringUtils.isNotBlank(endTime)) {
            map.put("endTime", "create_time@" + DateUtil.format(endTimeDate, "yyyy-MM-dd") + " 23:59:59");
        }
        if (StringUtils.isNotBlank(beginTime)) {
            map.put("beginTime", "create_time@" + DateUtil.format(beginTimeDate, "yyyy-MM-dd") + " 00:00:00");
        }
        map.put("index", index);
        map.put("keywordsFields", keywordsFields);
        if (StringUtils.isNotBlank(keyWord)) {
            map.put("keywords", keyWord);
        }
        if (userId > 0) {
            map.put("user_id", userId);
        }
        String requestParam = JSON.toJSONString(map);
        logger.info("search begin paramaters : {}", requestParam);
        Response response = okHttpUtils.doPost(ResourcesUtils.getESUrl(), requestParam);
        return getEsPager(response, pager);
    }


    private Pager<T> getEsPager(Response response, Pager<T> pager) {
        List<T> esNcnaDtos;
        try {
            if (response == null) {
                logger.error("rm-search***error***********response is null");
                return new Pager<>();
            }
            String result = response.body().string();
            String code = JSON.parseObject(result).getString("result");
            if (code != null && !code.equals("200")) {
                logger.error("rm-search***error*************result{}", result);
                return new Pager<>();
            }
            String obj = JSON.parseObject(result).getString("obj");
            if (StringUtils.isBlank(obj)) {
                logger.error("rm-search***obj=null**************result{}", result);
                return new Pager<>();

            }
            JSONObject dataObj = JSON.parseObject(obj);
            if (StringUtils.isBlank(dataObj.getString("datas"))) {
                logger.error("rm-search***data=null************obj{}", dataObj);
                return new Pager<>();
            }
            esNcnaDtos = JSON.parseObject(dataObj.getString("datas"), new TypeReference<List<T>>() {
            });
            pager.setData(esNcnaDtos);
            pager.setPage(Integer.parseInt(dataObj.getString("pageNumber")));
            pager.setCount(Integer.parseInt(dataObj.getString("totalRow")));
            pager.setPages(Integer.parseInt(dataObj.getString("totalPage")));
            pager.setLength(Integer.parseInt(dataObj.getString("pageSize")));
        } catch (IOException e) {
            e.printStackTrace();
            return new Pager<>();
        }
        return pager;
    }


}
